package com.qiaoya.deviceProxy;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MsgLinkService {
	
	private ServerHandler serverHandler = new ServerHandler();

	public static Map<String, IoSession> connectClient = new ConcurrentHashMap<String, IoSession>();

	public static int connectTimeout = 30000;

	private IoAcceptor acceptor = null;
	
	public void linkStart() {
		try {
			acceptor = new NioSocketAcceptor();
			TextLineCodecFactory lineCodec = new TextLineCodecFactory(Charset.forName("UTF-8"));
			lineCodec.setDecoderMaxLineLength(102400);
			lineCodec.setEncoderMaxLineLength(102400);
			acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(lineCodec));
			acceptor.getSessionConfig().setReadBufferSize(2048);
			acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
			acceptor.setHandler(serverHandler);
			Properties config = new Properties();
			// 读取属性文件a.properties
			InputStream in;
			String propPath = MsgLinkService.class.getClassLoader().getResource("application.properties").getPath();
			in = new BufferedInputStream(new FileInputStream(propPath));
			config.load(in);
			String host = config.getProperty("mina.host"); 
			String port = config.getProperty("mina.port");
			in.close();
			acceptor.bind(new InetSocketAddress(InetAddress.getByName(host), Integer.parseInt(port)));
			System.out.println("mina server started at " +host+":"+ port);
		} catch (Exception e) {
			e.printStackTrace();
			linkStop();
		}
	}

	/**
	 * stop link service
	 */
	public void linkStop() {
		if (acceptor != null) {
			acceptor.unbind();
			acceptor.dispose();
			while(true){
				if(acceptor.isCloseOnDeactivation()&&acceptor.isDisposed()&&!acceptor.isActive()){
					
					try {
						this.wait(1000);
						System.out.println("Unbind local address sucessful!");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					acceptor = null; 
					break;
				}
				System.out.println("Unbind local address ING!");
			}
		}
	}
}
